﻿/*
 * Copyright 2012 Rene Prost, Registrite ja Infosüsteemide Keskus 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Services.Description;
using System.Xml;
using log4net;
using System.Xml.Schema;

namespace Xtee.Core.Services.Description
{
    public class Port 
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Port));

        public XmlQualifiedName TargetNamespace { get; private set; }

        public IEnumerable<Operation> Operations { get; private set; }

        public ISchemaObjectResolver Resolver  { get; private set; }

        public SchemaSetCompiler Compiler { get; private set; }
        
        protected Port(XmlQualifiedName targetNamespace,Description description)
        { 
            var schemaSet = new XmlSchemaSet(); 
            Resolver = new SchemaObjectResolver(targetNamespace, schemaSet, description);
            TargetNamespace = targetNamespace;
            Compiler = new SchemaSetCompiler((SchemaObjectResolver)Resolver);  
        }
         
        public static Port Create(System.Web.Services.Description.Port port,Description description, bool justOperations)
        { 
            var operationBinding = port
                .Service
                .ServiceDescription
                .Bindings
                .First<Binding>(x => x.Name == port.Binding.Name);

           var soapBinding =  operationBinding.Extensions.OfType<SoapBinding>().FirstOrDefault();
            var targetNameSpace = port.Service.ServiceDescription.Namespaces.ToArray().ToList().First(x=>x.Namespace== port.Service.ServiceDescription.TargetNamespace);
            var ourPort = new Port(targetNameSpace, description);
            bool isStyleDocumentLiteral = soapBinding != null && soapBinding.Style == SoapBindingStyle.Document;

            if (!isStyleDocumentLiteral)
                throw new NotImplementedException("Wsdl must be in document/literal style.");
            
            var operations = operationBinding
                .Operations
                .Select<OperationBinding, Operation>(x => Operation.Create(ourPort, x, justOperations))
                .ToList();

            ourPort.Operations = operations;
            description.Port = ourPort;
            return ourPort;
        }
         
    }
}
